<template>
  <div>
    <div style="display: flex; align-item: center">
      <el-switch
        v-model="showAllProj"
        active-text="所有项目"
        inactive-text="当前项目"
        size="small"
        class="ml-2"
        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        @change="changeProject"
      />
      &nbsp; &nbsp; &nbsp;
      <div>
        <el-upload
          action="#"
          :http-request="uploadRequest"
          :show-file-list="false"
          style="display: inline-block"
          class="buttonposition"
        >
          <el-button type="primary" size="small">上传数据</el-button>
        </el-upload>
        &nbsp;
        <el-button @click="checkUpDate" type="primary" size="small"
          >查询已上传数据项目</el-button
        >
        <el-button type="danger" size="small" @click="clearProjectDatas"
          >清空数据</el-button
        >
      </div>
    </div>

    <div id="group1"></div>

    <div id="group2"></div>

    <div id="group3"></div>

    <el-dialog v-model="dialogFiles" title="附件列表" width="35%">
      <el-table size="default" :data="dioFiles" class="roledata" height="500">
        <el-table-column width="100" prop="proj_no" label="项目代号">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="proj_name"
          label="项目名称"
        >
        </el-table-column>
        <el-table-column width="100" prop="import_user" label="上传人">
        </el-table-column>
        <el-table-column prop="import_time" label="上传时间"> </el-table-column>
      </el-table>
      <div style="margin-top: 20px" class="upLoad">
        <el-button
          @click="Download"
          style="margin-right: 10px; margin-top: 10px"
          size="small"
          type="success"
          >下载数据</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import * as XLSX from "xlsx";
import { ref, reactive, onMounted, watch, shallowRef ,nextTick} from "vue";
import axios from "axios";
import * as echarts from "echarts";
import { useProjectStore } from "/@/stores/project";
import { storeToRefs } from "pinia";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  DeleteProjectDatas,
  ImportUserUnfinishedWorkDatas,
} from "../../api/project";
const projectStore = useProjectStore();
let { proj_no, proj_oid } = projectStore.projectInfo;

// 定义变量内容
let showAllProj = ref(false);

let action = ref("");
let projectDatas = ref([]);

// 上传文件请求
let uploadRequest = async (uploadFile) => {
  let formData = new FormData();
  //传给后台接收的名字 file
  formData.append("file", uploadFile.file);
  // 使用try catch 捕获异常
  try {
    await ImportUserUnfinishedWorkDatas(
      formData,
      proj_oid,
      JSON.parse(localStorage.getItem("userMessage")).user_name
    );
  } catch (error) {
    if (error.toString().includes("False")) {
      ElMessage({
        message: "上传失败",
        type: "error",
      });
    } else {
      ElMessage({
        message: "上传成功",
        type: "success",
      });
    }
    getprojworkload();
  }
};

let groupFirstEchartOptions = reactive({
  title: {
    text: "项目工作量情况",
    x: "center",
    top: "5%",
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      // Use axis to trigger tooltip
      type: "shadow", // 'shadow' as default; can also be 'line' or 'shadow'
    },
  },
  legend: {
    top: "10%",
    left: "center",
    itemWidth: 30,
    itemHeight: 20,
    textStyle: {
      fontSize: 16,
    },
  },
  grid: {
    top: "15%",
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    axisLabel: {
      fontSize: 14,
      interval: 0,
      rotate: 90,
    },
    axisTick: {
      aligWithLabel: true,
    },
    data: [],
  },
  yAxis: {
    type: "value",
  },
  series: [],
});

let groupSecondEchartOptions = reactive({
  title: {
    text: "项目工作量情况",
    x: "center",
    top: "5%",
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      // Use axis to trigger tooltip
      type: "shadow", // 'shadow' as default; can also be 'line' or 'shadow'
    },
  },
  legend: {
    top: "10%",
    left: "center",
    itemWidth: 30,
    itemHeight: 20,
    textStyle: {
      fontSize: 16,
    },
  },
  grid: {
    top: "15%",
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    axisLabel: {
      fontSize: 14,
      interval: 0,
      rotate: 90,
    },
    axisTick: {
      aligWithLabel: true,
    },
    data: [],
  },
  yAxis: {
    type: "value",
  },
  series: [],
});

let groupThirdEchartOptions = reactive({
  title: {
    text: "项目工作量情况",
    x: "center",
    top: "5%",
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      // Use axis to trigger tooltip
      type: "shadow", // 'shadow' as default; can also be 'line' or 'shadow'
    },
  },
  legend: {
    top: "10%",
    bottom: 50,
    left: "center",
    itemWidth: 30,
    itemHeight: 20,
    textStyle: {
      fontSize: 16,
    },
  },
  grid: {
    top: "15%",
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    axisLabel: {
      fontSize: 14,
    },
    axisTick: {
      aligWithLabel: true,
    },
    data: [],
  },
  yAxis: {
    type: "value",
  },

  series: [],
});
let group1 = shallowRef(null);
let group2 = shallowRef(null);
let group3 = shallowRef(null);

// 定义图表所需要的字段 中文字段和英文字段
let valueMap = [
  { label: "设计未完成工程图", value: "design_unfinished_engineering_drawing" },
  {
    label: "设计未完成施工图",
    value: "design_unfinished_construction_drawing",
  },
  { label: "校核未完成工程图", value: "check_unfinished_engineering_drawing" },
  { label: "校核未完成施工图", value: "check_unfinished_construction_drawing" },
  { label: "审核未完成工程图", value: "review_unfinished_engineering_drawing" },
  {
    label: "审核未完成施工图",
    value: "review_unfinished_construction_drawing",
  },
];




// 切换显示所有项目或当前项目
function changeProject() {
  getprojworkload();
}

// 下载文件
let Download = () => {
  // 创建工作表
  const ws = XLSX.utils.json_to_sheet(dioFiles.value);

  // 创建工作簿并添加工作表
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

  // 定义导出的文件名
  const fileName = "已上传数据.xlsx";

  // 写入XLSX文件
  XLSX.writeFile(wb, fileName);
};

let dialogFiles = ref(false);
let dioFiles = ref([]);

// 查询已上传数据项目
let checkUpDate = async () => {
  dialogFiles.value = true;
  let res = await axios.get(
    `/api/Analysis/GetAllProjectForUnfinishedWorkDatas`
  );

  dioFiles.value = res.data;
};

let proj_no_change = ref(null)
let proj_oid_change = ref(null)
let proj_name_change = ref(null)
// TODO:需适配切换项目后，图标数据更新
watch(projectStore, (newVal) => {
  proj_no_change.value = newVal.projectInfo.proj_no;
  proj_oid_change.value = newVal.projectInfo.proj_oid;
  proj_name_change.value = newVal.projectInfo.proj_name;
  console.log(proj_oid_change.value)
  nextTick(() => {
    getprojworkload();
  });
 
},{immediate:true});

// 获取项目数据
function getProjDatas() {
  //当前用户权限等于30时，调用接口获取该用户作为专业负责人的所有项目
  const userAuth = sessionStorage.getItem("userAuth");
  const loginAccount = sessionStorage.getItem("loginAccount");
  // 小于30时 无法看到这个界面
  if (userAuth === "30") {
    axios
      .get(
        `/api/project/GetProjectsForProfessionalLeader?userAccount=${loginAccount}`
      )
      .then((res) => {
        projectDatas.value = res.data;
      });
    return;
  }

  if (userAuth > 30) {
    axios.get("/api/project/getproject").then((response) => {
      projectDatas.value = response.data;
    });
  }
}

// 初始化echarts
function groupEchartsInit(groupId) {
  //柱形图
  //因为初始化echarts 的时候，需要指定的容器 id='main'
  let group = echarts.init(document.getElementById(groupId));
  return group;
}

async function getprojworkload() {
  let allUserDatas = [];
  // 获取当前项目中各用户未完成工作量
  if (!showAllProj.value) {
    await axios
      .get(
        `/api/Analysis/GetUserUnfinishedWorkDatasByProjIdV2?proj_oid=${proj_oid_change.value}`
      )
      .then((response) => {
        allUserDatas = response.data;
      });
  } else {
    await axios
      .get("/api/Analysis/GetUserUnfinishedWorkDatasV2")
      .then((response) => {
      
        allUserDatas = response.data;
      });
  }
  allUserDatas.forEach(v=>{
    Object.entries(v).forEach(([key,value])=>{
      if(value === 0){
        v[key] = "-"
      } 
    })
  })
 
  // 对进行图表进行赋值操作
  handleGroupDatas(allUserDatas, groupFirstEchartOptions, "设备一组");
  handleGroupDatas(allUserDatas, groupSecondEchartOptions, "设备二组");
  handleGroupDatas(allUserDatas, groupThirdEchartOptions, "工业炉");
 

  group1.value.setOption(groupFirstEchartOptions, true);
  group2.value.setOption(groupSecondEchartOptions, true);
  group3.value.setOption(groupThirdEchartOptions, true);
}

// 对数据进行赋值操作 （格式化数据）
function handleGroupDatas(allUserDatas, groupEchartOptions, groupName) {
  let oneSetDatas = allUserDatas.filter((obj) => obj.user_group === groupName);
 
  //清空上次数据
  groupEchartOptions.series.length = 0;
  groupEchartOptions.xAxis.data.length = 0;
 
  // 选择项目和没选择项目需要进行区分  选择项目时显示项目的具体名称
  if (proj_no_change.value) {
    if (oneSetDatas.length === 0) {
      
      groupEchartOptions.title.text = `${proj_no_change.value}项目人力负荷情况(${groupName})【数据未上传】`;
    } else {
      groupEchartOptions.title.text = `所有项目人力负荷情况(${groupName})`;
    }
  } else {
    groupEchartOptions.title.text = `所有项目人力负荷情况(${groupName})`;
  }

  if(!showAllProj.value){
    groupEchartOptions.title.text = `${proj_name_change.value}项目人力负荷情况(${groupName})`;
  }else{
    groupEchartOptions.title.text = `所有项目人力负荷情况(${groupName})`;
  }

  groupEchartOptions.xAxis.data = oneSetDatas.map((item) => item.user_name);

  for (let index = 0; index < valueMap.length; index++) {
    let serieName = valueMap[index].label;
    let serieData = oneSetDatas.map((item) => item[valueMap[index].value]);
    var obj = {
      name: serieName,
      type: "bar",
      barWidth: 30,
      stack: "total",
      label: {
        show: true,
      },
      emphasis: {
        focus: "series",
      },
      data: serieData,
    };
    groupEchartOptions.series.push(obj);
  }
}





// 清空选中项目数据
async function clearProjectDatas() {
  ElMessageBox.confirm("是否确认删除当前选中项目数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await DeleteProjectDatas({
      proj_oid: proj_oid,
    });
    getprojworkload();
    ElMessage({
      type: "success",
      message: "删除成功!",
    });
  });

  // 用户确认删除
  await this.$confirm("是否确认删除当前选中项目数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then((res) => {
      this.$axios({
        url: "/api/Analysis/DeleteProjectDatas",
        method: "GET",
        params: {
          proj_oid: this.proj_oid,
        },
      })
        .then((result) => {
          this.$message({
            message: "删除成功",
            type: "success",
            duration: 1000,
          });
          //更新柱状图
          this.getprojworkload();
        })
        .catch((err) => {});
    })
    .catch(() => {
      this.$message({
        type: "info",
        message: "已取消删除",
      });
    });
}



//#endregion

/* 定义生命周期函数 */
onMounted(() => {
  getProjDatas();
  // 初始化echart
  group1.value = groupEchartsInit("group1");
  group2.value = groupEchartsInit("group2");
  group3.value = groupEchartsInit("group3");
  // 在容器大小发生改变时，改变图表尺寸

  window.addEventListener("resize", () => {
    group1.value.resize();
    group2.value.resize();
    group3.value.resize();
  });
  getprojworkload();
});
</script>

<style scoped>
.setting {
  margin: 8px auto;
  background-color: #fff;
  border-radius: 5px;
}

.proj-select {
  margin-left: 20px;
}

.margin {
  margin: 4px 20px;
}

.container {
  width: 100%;
}

#group1,
#group2,
#group3 {
  margin: 8px auto 16px;
  height: 80vh;
  background-color: #fff;
  border-radius: 10px;
}
</style>
